import { useEffect, useState } from 'react';
import { App, Button, Descriptions, Select, Space, Tooltip } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import CloudTable from '@/component/CloudTable';
import { useTableDialog } from '@/hooks/useTable';
import { page as pageStaff } from "@/views/employee/staff/api";
import { batchRemoveClassStaff, findStaffByClassId, saveClassStaff } from '@/views/attendance/classInfo/api';
import { SEX_ENUMS, SEX_OPTIONS } from '@/views/employee/staff/data';
import { getTenantId } from '@/utils/storage';

const ClassDetail = ({ props = {} }) => {
    const { message } = App.useApp();

    const { date, selectedEvent, setSelectedEvent } = props;
    const [selectedStaffId, setSelectedStaffId] = useState(undefined);

    let items = [
        {
            label: '日期',
            children: date,
        },
        {
            label: '时间',
            span: 'filled',
            children: selectedEvent.beginTime + (selectedEvent.finishTime ? (' ~ ' + selectedEvent.finishTime) : ''),
        },
        {
            label: '备注',
            span: 'filled',
            children: selectedEvent.remark,
        },
    ];

    const staffColumns = [
        {
            title: '#',
            key: 'index',
            width: 50,
            align: 'center',
            fixed: 'left',
            render: (val, record, index) => {
                return index + 1;
            }
        },
        {
            title: '员工编码',
            dataIndex: 'code',
            key: 'code',
            width: 'auto',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            width: 'auto',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            width: 'auto',
            search: 'selected',
            options: SEX_OPTIONS(),
            render: (sex) => SEX_ENUMS[sex] || '',
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
            width: 'auto',
        },
    ];

    const [staffOptions, setStaffOptions] = useState([]);
    const onSearchStaffHandle = (val) => {
        let query = {
            params: [
                { field: 'name', expr: 'LIKE_LEFT', value: val },
                { field: 'tenantId', expr: 'EQ', value: getTenantId() },
            ]
        };
        pageStaff(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name + '(' + item.code + ')',
                value: item.id,
            }));
            setStaffOptions(options);
        });
    }

    const staffTools = () => (
        <Space>
            <Select
                showSearch
                allowClear
                size='small'
                placeholder="请输入姓名"
                optionFilterProp="label"
                filterOption={false}
                value={selectedStaffId}
                onSearch={(val) => onSearchStaffHandle(val)}
                onSelect={(val) => setSelectedStaffId(val)}
                options={staffOptions}
                style={{ width: 150 }}
            />
            <Button type="primary" size='small' onClick={addStaffHandler}>添加</Button>
            <Button color="danger" variant="dashed" size='small' onClick={() => staffTable.onBatchRemove(staffTable.selected)}>删除</Button>
        </Space>
    );

    const addStaffHandler = () => {
        if (!selectedStaffId) {
            message.warning('请选择员工');
            return;
        }
        let model = {
            classId: selectedEvent?.id,
            staffId: selectedStaffId,
            tenantId: getTenantId(),
        }
        saveClassStaff(model).then(resp => {
            if (resp?.data) {
                message.success('添加成功');
                setSelectedStaffId(undefined);
                staffTable.onReload();
            }
        });
    }

    const staffTable = useTableDialog({
        width: 400,
        // height: 280,
        reload: findStaffByClassId,
        batchRemove: batchRemoveClassStaff,
        tools: staffTools,
        columns: staffColumns,
    });

    useEffect(() => {
        if (selectedEvent) {
            let query = {
                id: selectedEvent?.id,
                data: {},
            }
            staffTable.onReload(query);
        }
    }, [selectedEvent]);

    return (
        <div>
            <Descriptions
                bordered
                title={selectedEvent.title}
                size='small'
                items={items}
                extra={
                    <Space>
                        <Tooltip title='返回'>
                            <Button
                                size='small'
                                type="text"
                                icon={<ArrowLeftOutlined style={{ color: '#1890ff' }} />}
                                onClick={() => setSelectedEvent(null)}
                            />
                        </Tooltip>
                    </Space>
                }
            />
            <div style={{ width: '100%', height: 395, marginTop: 8 }}>
                <CloudTable props={staffTable} />
            </div>
        </div>
    )
}

export default ClassDetail;